﻿<#
	.SYNOPSIS
		Cleans workspace folder from vs build artefacts - obj and bin subfolders
		Supports preview switch -WhatIf
	.DESCRIPTION
		Purges obj folder completely. 
		Bin folder without Interops subfolder. Leaves vshost-files. if other not specified		
	.PARAMETER RootPath
	  	Root path for clean
	.PARAMETER VsHosts
	  	Include vshost - files. Not included by default because they locked by VS
	.EXAMPLE
		Clear-Workspace -Path p:\como -WhatIf
		Dry run - preview what will be done without -WhatIf
	.EXAMPLE
		Clear-Workspace -Path p:\como
	.EXAMPLE
		Clear-Workspace 
		Cleans current folder
	.EXAMPLE
		Clear-Workspace -Path p:\como -Verbose
		Provide verbose output 	
#>

[CmdletBinding(SupportsShouldProcess=$True)]
Param(
    [parameter(ValueFromPipelineByPropertyName=$True)]
	[Alias("Path")]
	[string]$RootPath,
	[switch]$VsHosts
)

function Main()
{
	#if not specified take current directory
	if ([string]::IsNullOrEmpty($RootPath)){$RootPath=$PWD.Path}
	Write-Verbose "Process in Root Directory:$RootPath"

	$script:exclude=@("Interops")
	if ($VsHosts -eq $false) {$exclude+="*vshost*"}

	#lambda for recursing directories
	$walkDirs = {param($Path,[string]$Include) ls -Path $Path -Include $Include -Directory  -Recurse}
	
	#clean obj folder completely
	& $walkDirs $RootPath obj | Remove-Item -Recurse -Force 
	#clean bin folder with Clean-Folder helper
	& $walkDirs -Path $RootPath -Include bin | Clear-Directory
}

function Clear-Directory{
[CmdletBinding(SupportsShouldProcess=$True)]
param (
   [parameter(ValueFromPipelineByPropertyName=$True)]
   [Alias("FullName")]
   [string] $Path
)
	process{
		ls -Path $Path -Exclude $exclude | Remove-Item -Recurse -Force
		#not remove empty folder if -WhatIf specified
		if ($WhatIfPreference -eq $false){
			if (Test-DirectoryEmpty $Path) {Remove-Item $Path}
		}

	}
}

function Test-DirectoryEmpty{
param([string]$Path)
	$di = Get-ChildItem $Path -Force | Measure-Object
	$di.count -eq 0
}



Main